import {FuncBlock} from "../../../component/FuncBlock/FuncBlock.js";

/*
 * @param {object} proc - 初始化系数
 * @param {number} proc.serviceUUID - 服务 UUID
 * @param {number} proc.characteristicUUID - 特征 UUID
 * @param {string} proc.startMessage - 初始信息
 * @param {string} proc.endMessage - 结束信息
 * @param {string} proc.selector - 按钮选择器信息
 */

function bluetoothService(proc) {
    // 蓝牙设备
    this.bluetoothDevice = null;

    // 服务id
    this.serviceUUID = proc.serviceUUID || 0xffe0;
    // 特征id
    this.characteristicUUID = proc.characteristicUUID || 0xffe2;
    // 开始信息
    this.startMessage = proc.startMessage || "1";
    // 结束信息
    this.endMessage = proc.endMessage || "0";
    // 按钮
    this.button = proc.button;
    if(!this.button) return false;

    // 按钮初始化
    this.__initButton();
}

// 十六进制字符串转换为 Uint8Array
bluetoothService.prototype.hexToUint8Array = async function(hexString) {
    const bytes = [];
    for (let i = 0; i < hexString.length; i += 2) {
        bytes.push(parseInt(hexString.substr(i, 2), 16));
    }
    return new Uint8Array(bytes);
}

// 发送信息
bluetoothService.prototype.sendHexData = async function(serviceUUID, characteristicUUID, hexString) {
    if(this.bluetoothDevice === null) return false;

    let data = await this.hexToUint8Array(hexString);
    let characteristic = await this.bluetoothDevice.gatt.connect()
    .then((server) => {
        return server.getPrimaryService(serviceUUID || this.serviceUUID);
    })
    .then((service) => {
        return service.getCharacteristic(characteristicUUID || this.characteristicUUID);
    })
    .catch((error) => {
        console.error('Error sendHexData to Bluetooth device:', error);
        return false;
    });

    if(!characteristic) return false;

    // 发送信号
    for(let i = 0;i < 3;i++) {
        await characteristic.writeValue(data)
        .then(() => {
            console.log("Hex data sent successfully.");
        })
        .catch(error => {
            console.error("Error sending hex data:", error);
        });
    }
}

// 取消连接
bluetoothService.prototype.__bluetoothDisLink = async function() {
    if (this.bluetoothDevice != null) {
        await this.sendHexData(this.serviceUUID, this.characteristicUUID, this.endMessage);
        await this.bluetoothDevice.gatt.disconnect();
        this.bluetoothDevice = null;
    }
    setTimeout(() => {
        this.button.checked = false;
    }, 500);
}

// 连接
bluetoothService.prototype.__bluetoothLink = async function() {
    // @ts-ignore
    this.bluetoothDevice = await navigator.bluetooth.requestDevice({
        filters: [{
            services: [this.serviceUUID]
        }],
        optionalServices: [this.serviceUUID],
    })
    .catch(error => {
        // 错误处理
        console.error('Error accessing Bluetooth device:', error);
        this.__bluetoothDisLink();
        return null;
    });

    if(this.bluetoothDevice != null) {
        alert("The device is connected successfully. You can start the operation.");
        await this.bluetoothDevice.gatt.connect();
        setTimeout(() => {
            this.sendHexData(this.serviceUUID, this.characteristicUUID, this.startMessage);
        }, 500);
    }
}

// 按钮初始化
bluetoothService.prototype.__initButton = function() {
    this.button.addEventListener("click", () => {
        if(this.button.checked)
            this.__bluetoothLink();
        else
            this.__bluetoothDisLink();
    })
}

function createBluetoothService(proc) {
    return new bluetoothService(proc || null);
}

// 蓝牙连接功能块
let bluetoothLinkFuncBlock = FuncBlock(document.querySelector(".bluetoothLinkFuncBlock"));

function initBluetoothLinkFuncBlock() {
    bluetoothLinkFuncBlock.setIcon("./img/DeviceControl/FuncBlock/链接.svg");
    bluetoothLinkFuncBlock.setText("Link Device");
    bluetoothLinkFuncBlock.setSize(1);
    let timeout = null;
    window.addEventListener("resize", () => {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            bluetoothLinkFuncBlock.setSize(1);
        }, 200);
    });
}
initBluetoothLinkFuncBlock();

export var theService = createBluetoothService({serviceUUID: 0xffe0, characteristicUUID: 0xffe2, button: bluetoothLinkFuncBlock.getCheckBox()})

const P2DataPlateSlider = document.querySelector("#page_2 .dataPlate input");
var serviceUUID = 0xffe0;
var characteristicUUID = 0xffe2;
var timeoutSign = null;

// 获取盘数值
function getDataPlateValue() {
    // @ts-ignore
    return String(Math.ceil(P2DataPlateSlider.value / 20));
}

function addSliderListAndSendData() {
    if(P2DataPlateSlider === null) {
        return false;
    }
    P2DataPlateSlider.addEventListener("input", () => {
        clearTimeout(timeoutSign);
        timeoutSign = setTimeout(() => {
            theService.sendHexData(serviceUUID, characteristicUUID, getDataPlateValue());
        }, 500);
    })
}
addSliderListAndSendData();